<?php
class Madmin extends CI_Model{
	function __construct(){
		parent::__construct();
	}
	function login($username,$pwd){
		$sql = "select *
				from tbadmin
				where username = ? and pwd = ? and isvalid = 1";
		$query = $this->db->query($sql,array("$username","$pwd"));
		return $query->result();
	}
	
	function updateLoginIP($username,$ip){
		$sql = "update tbadmin
				set lastloginip = ?,lastlogintime=now()
				where username = ?";
		$query = $this->db->query($sql,array("$ip","$username"));
	}
	function loadAdmin(){
		$sql = "select a.*,case when a.isvalid = 1 then '有效' else '无效' end isvalidname
				from tbadmin a
				order by id asc";
		$query = $this->db->query($sql);
		return $query->result();
	}
	function checkExistsAdminForUpdate($id,$username){
		$sql = "select *
				from tbadmin
				where id!=? and username = ?";
		$query = $this->db->query($sql,array("$id","$username"));
		foreach ($query->result() as $row){
			return true;
		}
		return false;
	}
	function checkExistsAdmin($username){
		$sql = "select *
				from tbadmin
				where username = ?";
		$query = $this->db->query($sql,array("$username"));
		foreach ($query->result() as $row){
			return true;
		}
		return false;
	}
	function modifyAdmin($id,$pwd,$isvalid){
		$sql = "update tbadmin set pwd = ?,isvalid= ? where id = ?";
		$this->db->query($sql,array("$pwd","$isvalid","$id"));
	}
	function addAdmin($username,$pwd,$isvalid){
		$sql = "insert into tbadmin(username,pwd,isvalid,isdefault,createtime) values(?,?,$isvalid,1,now())";
		$this->db->query($sql,array("$username","$pwd"));
	}
	function delAdmin($ids){
		$sql =" delete from tbadmin where id in $ids";
		$this->db->query($sql);
	}
	function setDefault($ids){
		$sql = "update tbadmin
				set isdefault = case when isdefault = 1 then 0 else 1 END
				where id in $ids";
		$this->db->query($sql);
	}
	function getAdminById($id){
		$sql = "select *
				from tbadmin
				where id = ?";
		$query = $this->db->query($sql,array("$id"));
		$arr = array();
		foreach ($query->result() as $row){
			$arr["id"] = $row->id;
			$arr["username"] = $row->username;
			$arr["pwd"] = $row->pwd;
			$arr["isvalid"] = $row->isvalid;
		}
		return $arr;
	}
}
?>